package com.yk.pool.command;

import com.yk.pojo.ReqMessage;
import com.yk.pojo.RespMessage;
import com.yk.pool.CommonInterface;
import com.yk.server.RPCClass;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.beanutils.MethodUtils;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by dingkl on 2017/7/27.
 */
public class MessageRevCommand implements CommonInterface {

    private ReqMessage reqMessage;

    private ChannelHandlerContext ctx;

    private RespMessage respMessage;

    public MessageRevCommand(ReqMessage reqMessage, ChannelHandlerContext ctx) {
        this.reqMessage = reqMessage;
        this.ctx = ctx;
        respMessage = new RespMessage();
    }

    @Override
    public void execute() throws Exception {
        Object object = RPCClass.getInstace().get(reqMessage.getClassName());
        if (object != null) {
            respMessage.setMessageId(reqMessage.getMessageId());
            Object o = ((Class)object).newInstance();
            Object result = MethodUtils.invokeMethod(o, reqMessage.getMethodName(), reqMessage.getObjects());
            respMessage.setCode("0000");
            respMessage.setMsg("成功");
            respMessage.setData(result);
        } else {
            respMessage.setCode("2222");
            respMessage.setMsg("未提供该服务" + reqMessage.getClassName());
        }

        ctx.writeAndFlush(respMessage).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                System.out.println("send-"+respMessage.getMessageId());
            }
        });
    }

    @Override
    public void handlerExecute(Runnable r, ThreadPoolExecutor executor) throws Exception {

    }

}
